package top.z.work.framework.jackson.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import jakarta.annotation.Nullable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.z.work.framework.common.util.JsonUtil;
import top.z.work.framework.jackson.core.databind.LocalDateTimeDeserializer;
import top.z.work.framework.jackson.core.databind.LocalDateTimeSerializer;

import java.time.LocalDateTime;

@Slf4j
@Configuration
public class JacksonConfiguration {

    @Bean
    public BeanPostProcessor objectMapperBeanPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(@Nullable Object bean, @Nullable String beanName) throws BeansException {
                if (!(bean instanceof ObjectMapper objectMapper)) {
                    return bean;
                }
                /**
                 * 1. 新增Long类型自动序列化为字符串类型
                 * 2. 新增LocalDateTime序列化反序列化规则
                 */
                SimpleModule simpleModule = new SimpleModule()
                        .addSerializer(Long.TYPE, ToStringSerializer.instance)
                        .addSerializer(Long.class, ToStringSerializer.instance)
                        .addSerializer(LocalDateTime.class, LocalDateTimeSerializer.INSTANCE)
                        .addDeserializer(LocalDateTime.class, LocalDateTimeDeserializer.INSTANCE);

                objectMapper.registerModules(simpleModule);

                JsonUtil.init(objectMapper);
                log.info("初始化 jackson 自动配置");
                return bean;
            }
        };
    }

}
